package com.vanysoft.business.base.customer.controller;

import com.vanysoft.business.base.customer.controller.demo.CustomerDemo;
import com.vanysoft.business.base.customer.service.BaseCustomerService;
import com.vanysoft.business.base.tag.service.BaseTagService;
import com.vanysoft.business.base.user.service.BaseUserService;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.common.utils.Excel.ExcelUtil;
import com.vanysoft.common.utils.string.StringUtil;
import com.vanysoft.framework.aop.VanySoftAspectException;
import com.vanysoft.framework.aop.VanySoftValidation;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.constants.DbConstants;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.JSONResponse;
import com.vanysoft.framework.validation.VanySoftValidationErr;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 类名称：BaseCustomerAction
 * 类描述：外部人员
 * 创建人：SharpClaw_x
 * 创建时间：2017年5月31日 上午10:55:26
 * 修改人：SharpClaw_x
 * 修改时间：2017年5月31日 上午10:55:26
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@RestController
@RequestMapping("/base/customer")
public class BaseCustomerAction extends BaseController {

    private final BaseCustomerService customerService;

    private final BaseTagService baseTagService;

    private final BaseUserService baseUserService;

    public BaseCustomerAction(BaseCustomerService customerService, BaseTagService baseTagService, BaseUserService baseUserService) {
        this.customerService = customerService;
        this.baseTagService = baseTagService;
        this.baseUserService = baseUserService;
    }

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @VanySoftValidation
    public JSONResponse addCustomer(@Valid CustomerDemo customer, BindingResult result) throws VanySoftAspectException, VanySoftBaseException {
        customerService.addCustomer(customer);
        return new JSONResponse();
    }

    /**
     * Function Name               delCustomerBatch
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月21日 上午9:43:50           SharpClaw_x      Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/delCustomer", method = RequestMethod.POST)
    public JSONResponse delCustomerBatch(String tagUserIds) {
        customerService.delCustomerBatch(tagUserIds);
        return new JSONResponse();
    }

    /**
     * Function Name               excelImportUser
     *
     * @param request
     * @param file
     * @return
     * @throws InvalidFormatException
     * @throws IOException
     * @throws VanySoftBaseException
     * @description 外部人员批量导入
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月13日 上午9:44:06           SharpClaw_x      Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/import")
    public JSONResponse excelImportUser(MultipartFile file, String tagCode, String repeatDeal) throws InvalidFormatException, IOException, VanySoftBaseException {

        if (StringUtils.isEmpty(tagCode)) {
            throw new VanySoftBaseException(MessageCodeConstant.ExcelException.TAG_NULL_ERROR);
        }

        Workbook workbook = ExcelUtil.createByFactory(file);
        //人员数据库重复提示
        String tip1 = null;
        //excel数据重复提示
        String tip2 = null;
        if (StringUtils.equals(repeatDeal, DbConstants.USER_COVER)) {
            tip1 = "已覆盖原有数据";
            tip2 = "保存最后一条数据";
        } else {
            tip1 = "已忽雷本次数据";
            tip2 = "保存第一条数据";
        }

        List<String> repeatErr = new ArrayList<String>();
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet != null) {
            //移除标题行
            sheet.removeRow(sheet.getRow(0));
            //移除标题行
            sheet.removeRow(sheet.getRow(1));
            List<Row> rows = ExcelUtil.readExcelContent(sheet);

            String userCode = null;
            String userName = null;
            String gender = null;
            String mobile = null;
            String email = null;
            String wechat = null;
            String jobPosition = null;

            List<String> contentVal = new ArrayList<String>();
            List<String> userCodeList = new ArrayList<String>();
            List<CustomerDemo> users = new ArrayList<CustomerDemo>();
            for (Row row : rows) {
                String result = "第" + (row.getRowNum() + 1) + "行：";

                userName = ExcelUtil.getCellValue(row.getCell(0)).trim();
                userCode = ExcelUtil.getCellValue(row.getCell(1)).trim();
                gender = ExcelUtil.getCellValue(row.getCell(2)).trim();
                wechat = ExcelUtil.getCellValue(row.getCell(3)).trim();
                mobile = ExcelUtil.getCellValue(row.getCell(4)).trim();
                email = ExcelUtil.getCellValue(row.getCell(5)).trim();
                jobPosition = ExcelUtil.getCellValue(row.getCell(6));


                if (StringUtils.isNotEmpty(userCode)) {
                    userCodeList.add(userCode);
                }

                if (!StringUtil.checkRegex(userCode, StringUtil.codeRegex)) {
                    result += "用户账号格式错误；";
                }
//				通过repeatDeal参数判断重复时处理方法，不做重复判断
                if (!baseUserService.checkUsercode(userCode)) {
                    repeatErr.add("用户编号：" + userCode + "重复，" + tip1);
                }

                if (!StringUtil.checkRegex(userName, StringUtil.nameRegex)) {
                    result += "用户姓名格式错误；";
                }

                if (StringUtils.isNotEmpty(mobile) && !StringUtil.checkRegex(mobile, StringUtil.mobileRegex)) {
                    result += "手机号码长度过长";
                }

                if (StringUtils.isNotEmpty(email) && !StringUtil.checkRegex(email, StringUtil.emailRegex)) {
                    result += "邮件格式错误；";
                }

                if (StringUtils.isNotEmpty(wechat) && !StringUtil.checkRegex(wechat, StringUtil.wechatRegex)) {
                    result += "微信号长度5~20；";
                }

                if (!StringUtils.equals(result, "第" + (row.getRowNum() + 1) + "行：")) {
                    contentVal.add(result);
                }

                CustomerDemo user = new CustomerDemo();
                user.setUserAccount(userCode);
                user.setUserName(userName);
                user.setGender(StringUtils.equals(gender, "男") ? "1" : "0");
                user.setMobile(mobile);
                user.setEmail(email);
                user.setWechat(wechat);
                user.setJobPosition(jobPosition);
                //非外部人员
                user.setTags(tagCode);

                users.add(user);
            }

            List<String> excelRepeat = StringUtil.checkListRepeat(userCodeList);
            for (String userId : excelRepeat) {
                repeatErr.add("用户编号：" + userId + "excel中重复，" + tip2);
            }


            List<VanySoftValidationErr> validationlist = new ArrayList<VanySoftValidationErr>();
            VanySoftValidationErr contentErr = null;

            if (contentVal.size() > 0) {
                contentErr = new VanySoftValidationErr();
                contentErr.setField("内容校验结果");
                contentErr.setMessage(contentVal.toArray(new String[0]));
                validationlist.add(contentErr);
            }

            if (validationlist.size() > 0) {
                throw new VanySoftValidationException(MessageCodeConstant.ExcelException.VALIDATION_RESULT, validationlist);
            } else {
                customerService.addExcelCustomer(users, repeatDeal);
            }
        }

        return new JSONResponse(MessageCodeConstant.RTN_CODE_SUCCESS, repeatErr);
    }


    /**
     * Function Name               loadTag
     *
     * @return
     * @throws VanySoftBaseException
     * @description 加载分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月13日 上午10:32:41           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/load", method = {RequestMethod.GET})
    public JSONResponse loadTag(@SessionUser UserInfo userInfo) throws VanySoftBaseException {
        List<Map> resultList = baseTagService.loadTag(DbConstants.OUTSIDE_TAG_OWNER, userInfo.getId());
        return new JSONResponse(resultList);

    }

    /**
     * Function Name               addTag
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 添加分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月13日 上午10:32:56           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/addTag", method = {RequestMethod.POST})
    public JSONResponse addTag(@SessionUser UserInfo userInfo, HttpServletRequest request) throws VanySoftBaseException {
        String paretTagCode = request.getParameter("paretTagCode");
        String tagName = request.getParameter("tagName");
        Map tagMap = baseTagService.addTag(DbConstants.OUTSIDE_TAG_OWNER, tagName, paretTagCode, userInfo.getId());
        return new JSONResponse(tagMap);
    }

    /**
     * Function Name               modifyTag
     *
     * @param request
     * @return
     * @description 修改分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月13日 上午10:33:11           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/modifyTag", method = {RequestMethod.POST})
    public JSONResponse modifyTag(HttpServletRequest request) {
        String tagCode = request.getParameter("tagCode");
        String tagName = request.getParameter("tagName");
        baseTagService.modifyTag(tagCode, tagName);
        return new JSONResponse();

    }

    /**
     * Function Name               deleteTag
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 删除分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月13日 上午10:33:26           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/deleteTag", method = {RequestMethod.POST})
    public JSONResponse deleteTag(HttpServletRequest request) throws VanySoftBaseException {
        String tagCode = request.getParameter("tagCode");
        baseTagService.deleteTag(tagCode);
        return new JSONResponse();
    }

    /**
     * Function Name               queryTagUser
     *
     * @param request
     * @return
     * @description 查询分类人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 上午11:36:48           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryTagUser", method = {RequestMethod.GET})
    public JSONResponse queryTagUser(HttpServletRequest request) {
        String tagCode = request.getParameter("tagCode");
        String searchContent = request.getParameter("searchContent");
        String pageIndex = request.getParameter("pageIndex");
        if (StringUtils.isEmpty(pageIndex)) {
            pageIndex = "1";
        }
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        Map result = baseTagService.queryTagUser(tagCode, Integer.parseInt(pageIndex), Integer.parseInt(pageSize), searchContent);
        return new JSONResponse(result);

    }
}
